package packet

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"os"
)

type NPacket struct {
	Version int16
	ID      uint32
	Buffer  [1024]byte
}

func (packet *NPacket) String() string {
	return fmt.Sprintf("%v, %v, %v\n", packet.Version,
		packet.ID, string(packet.Buffer[:]))
}

func CheckError(err error) {
	if err != nil {
		fmt.Println("Error: %s", err.Error())
		os.Exit(1)
	}
}

func ConvertToPacket(b []byte) (packet *NPacket, err error) {
	buffer := bytes.NewBuffer(b[:])

	packet = &NPacket{}
	err = binary.Read(buffer, binary.BigEndian, packet)

	return packet, err
}

func ConvertToBuffer(packet *NPacket) (b []byte, err error) {
	buf := new(bytes.Buffer)

	err = binary.Write(buf, binary.BigEndian, packet)

	return buf.Bytes(), err
}
